package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/dgrijalva/jwt-go/request"
	"github.com/kataras/iris/v12"
	"go-movies/model"
	"reflect"
	"time"
)

const (
	JWTSecret = "chenSir#$@%_"
)

// 生成token:
func GetToken(username string, email string) string {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": username,
		"email": email,
		"exp": time.Now().Add(time.Hour * 24).Unix(),
	})
	tokenString, _ := token.SignedString([]byte(JWTSecret))
	return tokenString
}

// 验证TOKEN中间件
func ValidateJwtMiddleware(ctx iris.Context) {
	token, err := request.ParseFromRequest(ctx.Request(), request.AuthorizationHeaderExtractor, func(token *jwt.Token) (i interface{}, e error) {
		return []byte(JWTSecret), nil
	})
	if err != nil || !token.Valid {
		model.HandleErrorModel(ctx, 403, "System prompt: You have not logged in, please log in first")
	}else{
		ctx.Next()
	}
}

// 获取JWT中的值
func GetJWTValue(ctx iris.Context, key string) string {
	token, _ := request.ParseFromRequest(ctx.Request(), request.AuthorizationHeaderExtractor, func(token *jwt.Token) (i interface{}, e error) {
		return []byte(JWTSecret), nil
	})
	v := reflect.ValueOf(token.Claims)
	if v.Kind() == reflect.Map {
		for _, k := range v.MapKeys() {
			value := v.MapIndex(k)
			if fmt.Sprintf("%s", k.Interface()) == key {
				return fmt.Sprintf("%v", value.Interface())
			}
		}
	}
	return ""
}